import { defineStore } from "pinia"

import langs from '@/i18n/lang'
import { dictionaryItemByCategoryApi } from "@/api/system/Dictionary"
import { refreshLoginApi } from "@/api/Login"
import { configsApi } from "@/api/system/Config"



let loginAuth = false
let token = localStorage.getItem(import.meta.env.B_TOKEN_KEY)
let expire = localStorage.getItem(import.meta.env.B_TOKEN_EXPIRE_KEY)
if(token && expire) {
    let offset = Number(expire) - (new Date()).getTime()
    if(offset > 600 * 1000) {
        loginAuth = true
    }
}

let userInfo:any = localStorage.getItem(import.meta.env.B_USER_KEY)
if(userInfo) {
    userInfo = JSON.parse(userInfo)
}



export const useSysConfigStore = defineStore<string, {staticUrl:string; videoUrl:string}, {}, {init : () => Promise<void>}>('location', {
    state : () => ({
        staticUrl : '',
        videoUrl : '',
    }),

    actions : {
        async init () {
            configsApi().then(r => {
                let staticUrl = r.data.staticUrl as string
                let videoUrl = r.data.videoUrl as string

                if(!staticUrl.endsWith("/")) {
                    staticUrl = staticUrl + '/'
                }

                if(!videoUrl.endsWith("/")) {
                    videoUrl = videoUrl + '/'
                }

                this.staticUrl = staticUrl
                this.videoUrl = videoUrl
            })
        }
    }
})

export const useLocationStore = defineStore<string, {longitude:number; latitude:number}>('location', {
    state : () => ({
        longitude : 0,
        latitude : 0,
    })
})


export const useRouterTagsStore = defineStore<string, {tags:any[]; paths:any[]}>('routerTags', {
    state : () => ({
        tags : [],
        paths : [],
    }),

    actions : {
        add(tag:any) {
            if(!this.paths.includes(tag.path)) {
                this.tags.push(tag)
                this.paths.push(tag.path)
            }
            
        }
    }
})

export const useAuthStore = defineStore<string, {auth : boolean, userInfo:{belong : 0|1, super : boolean, dept:number, name : string}}, {}, 
{setUserInfo : (data:any) => void; setAuth:(data:boolean)=>void; setToken : (token:string, expire:number) => void; logout:()=>void; handleLoginData:(data:any) => void; refresh:() => Promise<void>}>('auth', {
    state : () => ({
        auth : loginAuth,
        userInfo : userInfo
    }),

    actions : {
        setUserInfo(userInfo) {
            this.userInfo = userInfo
            localStorage.setItem(import.meta.env.B_USER_KEY, JSON.stringify(userInfo))
        },

        setAuth(auth:boolean) {
            this.auth = auth
        },

        setToken(token:string, expire:number) {
            localStorage.setItem(import.meta.env.B_TOKEN_KEY, token)
            localStorage.setItem(import.meta.env.B_TOKEN_EXPIRE_KEY, String((new Date()).getTime() + expire * 1000))
        },

        logout() {
            localStorage.removeItem(import.meta.env.B_TOKEN_KEY)
            localStorage.removeItem(import.meta.env.B_TOKEN_EXPIRE_KEY)
            this.auth = false
        },

        handleLoginData(data) {
            this.setUserInfo({
                name : data.name,
                super : data.super,
                belong : data.belong
            })
            this.setAuth(true)
            this.setToken(data.accessToken, data.expire)

        },

        async refresh() {
            const time = Number(localStorage.getItem(import.meta.env.B_TOKEN_EXPIRE_KEY))
            let offset = Number(time) - ((new Date()).getTime())


            console.log('剩余:' + offset)
            console.log((new Date()).toLocaleTimeString())

            if(offset <= 600 * 1000) {
                const r = await refreshLoginApi()
                if(r.success) {
                    this.handleLoginData(r.data)
                }
            }

            setTimeout(() => {
                this.refresh()
            }, 10 * 60 * 1000)
        }
    },
})


export const useLangStore = defineStore<string, {locales : string[], locale : keyof typeof langs, local : {[key:string] : string}, langs : {[key:string] : string}[]}, {langOptions : () => {label:string, value:string}[]}, {setLocale : (locale : keyof typeof langs) => void, initLang : () => Promise<any>, translate : (key:string, args?:Array<string|number>) => string}>('langStore', {
    state : () => ({
        locales : ['ZH', 'EN'],
        locale : (import.meta.env.B_DEFAULT_LOCALE).toLowerCase(), //当前语言类别
        local : {},
        langs : [],
    }),

    getters : {
        langOptions () {
            return this.langs.map(lang => ({label : lang[this.locale], value : lang.key}))
        }
    },

    actions : {
        setLocale(locale) {
            this.locale = locale
            localStorage.setItem(import.meta.env.B_LOCALE_KEY, locale)
        },
        async initLang() {
            let _locale = localStorage.getItem(import.meta.env.B_LOCALE_KEY) as keyof typeof langs
            if(_locale) {
                this.locale = _locale
            }

            this.local = {...langs[this.locale]}
            
            
        },

        translate(key:string, args:Array<string|number>) {
            let word:string = key.split('.').reduce((a, b) => {
                return a[b]
            }, this.local)
            return word
        }
    }
})




export const useDictStore = defineStore<
    string, 
    {
        dict : {[key:string] : Array<{name:string, code:string}>},
        TYPESOFMEMEBER : Array<{code : number, name : string}>,
        TASKSTATUS : Array<{code : number, name : string}>,
        EXECUTESTATUS : Array<{code : number, name : string}>,
        APPROVESTATUS : Array<{code : number, name : string}>
    }, 
    {}, 
    {
        get : (category:string) => Promise<Array<{code : string, name : string}>>
    }
>('dictStore', {
    state : () => ({
        dict : {
            
        },

        TYPESOFMEMEBER : [],
        TASKSTATUS : [],
        EXECUTESTATUS : [],
        APPROVESTATUS : []
        
    }),
    actions : {
        async get(category:string) {
            if(!this.dict[category]) {
                const langStore = useLangStore()
                const { data } = await dictionaryItemByCategoryApi(category)
                this.dict[category] = data.map(v => ({code : v.code, name : langStore.translate(v.name)}))
            }

            return this.dict[category]
        },


        
    }
})